// pages/orders_queren/orders_queren.js
const app = getApp()
import request from '../../utils/http.js'
// var qqmapsdk;
// const chooseLocation = requirePlugin('chooseLocation');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    mingCheng: '',
    logoImg: '',
    IsLogin: false,
    shopId: 0, //店铺ID

    fengMianList: [], //预购产品封面list
    zongJianShu: 0,
    shangPinJinE: 0,
    chanPinLeiXing:0,
    yunFen: 0,
    zongJinE: 0,
    shiFuKuan: 0,



    userName: '', //联系人
    provinceName: '', //省
    cityName: '',
    countyName: '', //区
    detailInfo: '', //详细地址
    telNumber: '', //联系电话

    shop_provinceName:'',
    shop_cityName:'',
    shop_areaName:'',
    shop_diZhi:'',
    shop_name:'',
    shop_phone:'',
    isZiTi:false,

    latitude: 0,
    longitude: 0,
    markers: [],

    scrollFlag: false,
    isClick: false, //确认支付是否点击
    orderFormId: 0, //订单id

    payType:1,//微信支付 2 信用卡分期
    productId: 0, //直接购买产品ID
    goumaiCount: 0, //直接购买产品数量
    zengSongChanPinId:0,
    guid:'',
    shopBuyerGuid:'',
    xianXiaXiangMuList:[],
    xianXiaFuWuShuLiang:0,
    sex:0,
    name:'',

    MenuButtonTop:50,
    MenuButtonHeight:30,
    huiYuanZheKouJinE:0,//会员优惠金额
    isHuiYuan:0,//1没有会员卡，2有会员卡

    yh_able:false,
    yh_jine:0,
    yh_count:0,
    list_YouHuiQuan:[],
    youHuiQuanId:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    that.setData({
      MenuButtonTop:app.globalData.MenuButtonTop,
      MenuButtonHeight:app.globalData.MenuButtonHeight,
     
      IsLogin: wx.getStorageSync(app.globalData.LOGINSTATUS),
      mingCheng: wx.getStorageSync(app.globalData.ShopName),
      shopId: wx.getStorageSync(app.globalData.SHOPID),
      logoImg: wx.getStorageSync(app.globalData.ShopLogo),
      userName: wx.getStorageSync(app.globalData.USERNAME), //联系人
      provinceName: wx.getStorageSync(app.globalData.PROVINCENAME), //省
      cityName: wx.getStorageSync(app.globalData.CITYNAME),
      countyName: wx.getStorageSync(app.globalData.COUNTYNAME), //区
      detailInfo: wx.getStorageSync(app.globalData.DETAILINFO), //详细地址
      telNumber: wx.getStorageSync(app.globalData.TELNUMBER), //联系电话

      shop_name:wx.getStorageSync(app.globalData.NiCheng),
      shop_phone:wx.getStorageSync(app.globalData.PHONENUMBER),

      zengSongChanPinId:options.zengSongChanPinId,
      guid:options.guid,
      shopBuyerGuid:options.shopBuyerGuid,
      name:options.name,
      productId: options.productId,
      goumaiCount: options.goumaiCount
    })

    that.getGoumaiInfo()
    that.getShopAddress();
  },



  //直接购买：获取预先订单信息
  getGoumaiInfo: function () {

    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    var that = this
    let data = {
      fuWuBaoChanPinId: that.data.productId,
      zengSongChanPinId:that.data.zengSongChanPinId,
      jiuZhenRenGuid:that.data.guid

    }
    request.get('fuWuBaoOrderForm/yuLan', data, res => {
      console.log("服务包预览:" + JSON.stringify(res.data))
      that.setData({
        fengMianList: res.data.zhongXinChanPinList,
        zongJianShu: res.data.zongFenShu,
        shangPinJinE: res.data.zongJia,
        chanPinLeiXing:res.data.chanPinLeiXing,
        yunFen: res.data.yunFen,
        zongJinE: res.data.tongYiJiaGe,
        shiFuKuan: res.data.shiFuKuan,
        xianXiaXiangMuList:res.data.xianXiaXiangMuList,
        xianXiaFuWuShuLiang:res.data.xianXiaFuWuShuLiang,
        // sex:res.data.sex,
        // name:res.data.name,

        isHuiYuan:res.data.isHuiYuan,
        huiYuanZheKouJinE:res.data.huiYuanZheKouJinE,

        list_YouHuiQuan:res.data.list_YouHuiQuan,
        yh_count:res.data.list_YouHuiQuan.length,
        yh_jine:res.data.diYongQuanJinE,
        youHuiQuanId:res.data.youHuiQuanId
      })
      wx.hideLoading()
    })
  },


  //获取服务站地址
  getShopAddress: function () {

    var that = this
    let data = {
      dianPuId: that.data.shopId,
    }
    request.get('dianPu/dianPuAddress', data, res => {
      console.log("服务站地址:" + JSON.stringify(res.data))
      that.setData({
        shop_provinceName:res.data.provinceName,
        shop_cityName:res.data.cityName,
        shop_areaName:res.data.areaName,
        shop_diZhi:res.data.diZhi,
        latitude: res.data.mapWeiDu,
        longitude: res.data.mapJingDu,
      })


      var pointObj = {}
        pointObj.id = that.data.shopId
        pointObj.latitude = res.data.mapWeiDu,
        pointObj.longitude = res.data.mapJingDu,
        pointObj.width = 30, //图片显示宽度
        pointObj.height = 30, //图片显示高度
        pointObj.iconPath = '/image/shopAddress.png',
        pointObj.title = that.data.mingCheng

        that.data.markers.push(pointObj)

        that.setData({
          markers: that.data.markers
        })


      wx.hideLoading()

    })
  },

  //选择地址
  setAderssTap: function () {
    var that = this
    if (wx.chooseAddress) {
      wx.chooseAddress({
        success: function (res) {
          wx.setStorageSync(app.globalData.USERNAME, res.userName);
          wx.setStorageSync(app.globalData.PROVINCENAME, res.provinceName);
          wx.setStorageSync(app.globalData.CITYNAME, res.cityName);
          wx.setStorageSync(app.globalData.COUNTYNAME, res.countyName);
          wx.setStorageSync(app.globalData.DETAILINFO, res.detailInfo);
          wx.setStorageSync(app.globalData.TELNUMBER, res.telNumber);
          wx.setStorageSync(app.globalData.NATIONALCODE, res.nationalCode);
          wx.setStorageSync(app.globalData.POSTALCODE, res.postalCode);
          that.setData({
            userName: res.userName,
            provinceName: res.provinceName,
            cityName: res.cityName,
            countyName: res.countyName,
            detailInfo: res.detailInfo,
            telNumber: res.telNumber,
            nationalCode: res.nationalCode,
            postalCode: res.postalCode,
          })
        },
        fail: function () {


          wx.openSetting({
            success: (res) => {
              if (res.authSetting["scope.address"]) { ////如果用户重新同意了授权
                wx.chooseAddress({
                  success: function (ress) {
                    wx.setStorageSync(app.globalData.USERNAME, ress.userName);
                    wx.setStorageSync(app.globalData.PROVINCENAME, ress.provinceName);
                    wx.setStorageSync(app.globalData.CITYNAME, ress.cityName);
                    wx.setStorageSync(app.globalData.COUNTYNAME, ress.countyName);
                    wx.setStorageSync(app.globalData.DETAILINFO, ress.detailInfo);
                    wx.setStorageSync(app.globalData.TELNUMBER, ress.telNumber);
                    wx.setStorageSync(app.globalData.NATIONALCODE, ress.nationalCode);
                    wx.setStorageSync(app.globalData.POSTALCODE, ress.postalCode);
                    that.setData({
                      userName: ress.userName,
                      provinceName: ress.provinceName,
                      cityName: ress.cityName,
                      countyName: ress.countyName,
                      detailInfo: ress.detailInfo,
                      telNumber: ress.telNumber,
                      nationalCode: ress.nationalCode,
                      postalCode: ress.postalCode,
                    })

                  },
                })
              }
            }
          })
        }
      })
    } else {
      console.log('当前微信版本不支持chooseAddress');
    }

    // wx.chooseInvoiceTitle({
    //     success(res) {
    //          console.log("发票:"+JSON.stringify(res))
    //     }
    // })
  },


  //是否自提
  changeAddressTapy() {
   
    this.setData({
      isZiTi:!this.data.isZiTi,
    })

    var color= this.data.isZiTi?'#299cbe':'#ff813d'
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: color,
      animation: {
        duration: 400,
        timingFunc: 'easeIn'
      }
    })

  },

   //收货人输入
   nameInput(e) {

    var value = e.detail.value;
    this.setData({
      shop_name:value
    })
   },

  //电话输入
  phoneInput(e) {
    this.setData({
      shop_phone:e.detail.value
    })
  },

  //提交订单
  toOrdersInfo: function () {

    if (((this.data.detailInfo == '' || this.data.userName == '' || this.data.telNumber == '')&& !this.data.isZiTi)) { //地址信息是否填写完整

      wx.showToast({
        title: "请完整填写详细收货地址！", // 提示的内容
        icon: "none", // 图标，默认success
        duration: 3000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })

    }else if((this.data.shop_name == '' || this.data.shop_phone.length != 11)&&this.data.isZiTi){
      wx.showToast({
        title: "收货人信息不完整！", // 提示的内容
        icon: "none", // 图标，默认success
        duration: 3000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })

    } else if (this.data.isClick) { //是否重复提交
      wx.showToast({
        title: "订单处理中，请勿重复提交！", // 提示的内容
        icon: "none", // 图标，默认success
        duration: 3000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
      return
    } else { //开始提交订单
      var that = this
      that.setData({ //避免重复
        isClick: true
      })
      wx.showLoading({
        title: '处理中...',
        mask: true
      })
 
      that.wxPay();
    
    }
  },


  //微信支付 
  wxPay: function () {

    var that=this
 
      let data = {
        openId: wx.getStorageSync(app.globalData.OPENID),
        
        dianPuId:that.data.shopId,
        fuWuBaoChanPinId: that.data.productId,
        jiuZhenRenGuid:that.data.guid,
        zengSongChanPinId:that.data.zengSongChanPinId,

        wxUserName: that.data.isZiTi?that.data.shop_name:that.data.userName,
        wxPostalCode: that.data.postalCode,
        wxProvinceName:that.data.isZiTi?that.data.shop_provinceName:that.data.provinceName,
        wxCityName: that.data.isZiTi?that.data.shop_cityName:that.data.cityName,
        wxCountyName: that.data.isZiTi?that.data.shop_areaName:that.data.countyName,
        wxDetailInfo: that.data.isZiTi?that.data.shop_diZhi:that.data.detailInfo,
        wxNationalCode: that.data.nationalCode,
        wxTelNumber: that.data.isZiTi?that.data.shop_phone:that.data.telNumber,
        kuaiDiFangShi:that.data.isZiTi?3:1,
        youHuiQuanId:that.data.youHuiQuanId

      }
      // console.log(data)
      request.get('fuWuBaoOrderForm/addFuWuBaoOrderForm', data, res => {

        // console.log("直接提交订单:"+JSON.stringify(res.data))
        wx.hideLoading()
        that.setData({
          orderFormId: res.data.orderFormId, //订单ID，生成订单成功后跳转用
        })
        if (res.data.status == 1) {
          wx.requestPayment({
            timeStamp: res.data.map.timeStamp,
            nonceStr: res.data.map.nonce_str,
            package: 'prepay_id=' + res.data.map.prepay_id,
            signType: 'MD5',
            paySign: res.data.map.paySign,
            success: function (ress) {

              that.syncData()
              wx.showToast({
                title: "支付成功！服务项目请在'健康档案查看'，产品发货请在'我的订单'查看", // 提示的内容
                icon: "none", // 图标，默认success
                duration: 2000, // 提示的延迟时间，默认1500
                mask: false, // 是否显示透明蒙层，防止触摸穿透
                complete: function () {

                  setTimeout(function () {
                    wx.redirectTo({
                      url: '/pkg_wo/pages/allOrders/allOrders?index=0',
                    })
                  }, 3000)
                }
              })

            },
            fail: function (ress) {
              wx.showToast({
                title: "支付失败！", // 提示的内容
                icon: "none", // 图标，默认success
                duration: 1000, // 提示的延迟时间，默认1500
                mask: false, // 是否显示透明蒙层，防止触摸穿透
                complete: function () {

                  // setTimeout(function () {
                  //   wx.redirectTo({
                  //     url: '/pkg_wo/pages/allOrders/allOrders?index=0',
                  //   })
                  // }, 1000)
                }
              })
    
              that.setData({
                isClick: false
              })
            },
            complete: function (ress) {
              //console.log("payComplete:" + JSON.stringify(res.data))
            }
          });
          // that.zhifu(res.data.dingDanHao);
        } else { //订单生成失败

          wx.showToast({
            title: "订单生成失败！", // 提示的内容
            icon: "none", // 图标，默认success
            duration: 3000, // 提示的延迟时间，默认1500
            mask: false, // 是否显示透明蒙层，防止触摸穿透
            complete: function () {
              that.setData({
                isClick: false
              })
            }
          })
        }
      })

  },


  toYouHui:function(){
    this.setData({
      yh_able:!this.data.yh_able
    })
  },

    //登录同步健康数据
  syncData(){
      request.get('qiTa/tongBuJiuZhenRenAndGouMaiChanPin', null, res => {
        console.log("下单同步数据成功" )
      })
  },


    
  // //选择优惠券
  yhRadioChange(e){
    console.log('radio发生change事件，携带value值为：', e.detail.value)


    if(e.detail.value.length==0){//都不选
      this.setData({
        youHuiQuanId:0,
      })
        
    }else if (e.detail.value.length==1){ //选一个

      this.setData({
        youHuiQuanId:this.data.list_YouHuiQuan[e.detail.value[0]].youHuiQuanId
      })
    }else{
     
      var temId=0
      var temId0=this.data.list_YouHuiQuan[e.detail.value[0]].youHuiQuanId
      var temId1=this.data.list_YouHuiQuan[e.detail.value[1]].youHuiQuanId
    
      if (temId0!=this.data.youHuiQuanId) {
        temId=temId0
      }else{
        temId=temId1
      }

      this.data.list_YouHuiQuan.forEach((item, index) => {   
        
        if(temId==item.youHuiQuanId){
          item.xuanZhongZhuangTai=true     
        }else{
          item.xuanZhongZhuangTai=false     
        }
           
      })

      this.setData({
        youHuiQuanId:temId,
        list_YouHuiQuan:this.data.list_YouHuiQuan
      })
    }

    this.countJe();

  },


  //重新计算优惠金额
  countJe(){

    if(this.data.youHuiQuanId>0){
      this.data.list_YouHuiQuan.forEach((item, index) => {   
          
        if(this.data.youHuiQuanId==item.youHuiQuanId){
            this.setData({
              yh_jine:item.diYongQuanJinE_fen,
              shiFuKuan:this.data.zongJinE-this.data.huiYuanZheKouJinE-item.diYongQuanJinE_fen
            })
        }   
      })
    }else{//一个优惠券都不选
      this.setData({
        yh_jine:0,
        shiFuKuan:this.data.zongJinE-this.data.huiYuanZheKouJinE
      })
    }

  },


  //选择支付方式
  radioChange(e) {
    // console.log('radio发生change事件，携带value值为：', e.detail.value)
    this.setData({
      payType: e.detail.value
    })
  },



  //虚拟支付

  zhifu: function (dingDanHao) {

    var that = this

    console.log("dingDanHao:"+dingDanHao)

    let data = {
      dingDanHao: dingDanHao,
    }
    request.get('OrderForm20231109/xiuNiZhiFu', data, res => {
      wx.reLaunch({
        url: '/pkg_wo/pages/allOrders/allOrders?index=0',
      })
    })
  },


  //圖片滑动监控
  scrolltolower: function () {
    this.setData({
      scrollFlag: true
    })
  },

  scrolltoupper: function () {
    this.setData({
      scrollFlag: false
    })
  },

  //返回
  bindNavigateBack: function () {
    wx.navigateBack({
      delta: 1
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})